﻿
using ArtheaEngine.Model;
using System.Text;
using System.Collections.Generic;
using System.Collections;
namespace ArtheaEngine
{
    /// <summary>
    /// Handles displaying text in columns
    /// </summary>
    public struct Columns
    {
        /// <summary>
        /// The default width for a column
        /// </summary>
        public static readonly ushort DefaultWidth = 80;


        /// <summary>
        /// Gets the width of the player default.
        /// </summary>
        /// <param name="player">The player.</param>
        /// <param name="columns">The columns.</param>
        /// <returns></returns>
        private static ushort GetPlayerDefaultWidth(Player player, ushort columns)
        {
            return (ushort)(player.Account.Connection.ScreenWidth / columns);
        }

        /// <summary>
        /// Shows the specified player.
        /// </summary>
        /// <param name="player">The player.</param>
        /// <param name="columns">The columns.</param>
        /// <param name="objects">The objects.</param>
        public static void Show(Player player, ushort columns, IList objects)
        {
            Show(player, columns, GetPlayerDefaultWidth(player, columns), objects);
        }

        /// <summary>
        /// Displays a list of objects in columns
        /// </summary>
        /// <param name="player">the player viewing the columns</param>
        /// <param name="columns">the number of columns</param>
        /// <param name="width">the width of a column</param>
        /// <param name="objects">the list of objects to display in the columns as an array</param>
        public static void Show(IWritable player, ushort columns, ushort width, IList objects)
        {
            StringBuilder buf = new StringBuilder();

            for(var i = 0; i < objects.Count; )
            {
                var text = objects[i].ToString();

                var format = string.Format("{{0,-{0}}}", width + (text.Length - text.DisplayLength()));

                buf.AppendFormat(format, text);

                ++i;

                if (text.DisplayLength() >= width || (i % columns) == 0 || i == objects.Count)
                {
                    buf.AppendLine();
                }
            }

            player.Page(buf);
        }
    }
}
